package com.fjh.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjh.es.ProdEs;
import com.fjh.service.SearchService;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    /**
     * 根据分组id查询
     * @param tagId
     * @param current
     * @param size
     * @return
     */
    @Override
    public Page<ProdEs> searchProdByTagId(Long tagId, Integer current, Integer size) {
        Page<ProdEs> prodEsPage = new Page<>(current + 1, size, false);
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("tagList", tagId);
        return query(prodEsPage,queryBuilder,null,null);
    }

    /**
     *
     *根据目录
     * @param categoryId
     * @param current
     * @param size
     * @return
     */
    @Override
    public Page<ProdEs> searchProdByCategoryId(Long categoryId, Integer current, Integer size) {
        Page<ProdEs> prodEsPage = new Page<>(current + 1, size, false);
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("categoryId", categoryId);
        return query(prodEsPage,queryBuilder,null,null);
    }

    /**
     * 根据关键字
     * @param keywords
     * @param current
     * @param size
     * @param sort
     * @return
     */
    @Override
    public Page<ProdEs> searchProdByKeywords(String keywords, Integer current, Integer size, Integer sort) {
        Page<ProdEs> prodEsPage = new Page<>(current + 1, size, false);
        MatchQueryBuilder queryBuilder = null;
        if (StringUtils.hasText(keywords)){
            queryBuilder = QueryBuilders.matchQuery("prodName", keywords);
        }
        return query(prodEsPage,queryBuilder,keywords,sort);
    }

    private Page<ProdEs> query(Page<ProdEs> prodEsPage, AbstractQueryBuilder queryBuilder,String keywords,Integer sort){
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withQuery(queryBuilder);
        //排序   分页
        SortBuilder sortBuilder = mySort(sort);
        nativeSearchQueryBuilder.withSort(sortBuilder);
        long current = prodEsPage.getCurrent() - 1;
        long size = prodEsPage.getSize();
        nativeSearchQueryBuilder.withPageable(PageRequest.of((int) current, (int) size));

        if (StringUtils.hasText(keywords)){
            //组装查询条件
            HighlightBuilder.Field field = new HighlightBuilder.Field("prodName");
            field.preTags("<i style='color:red'>");
            field.postTags("</i>");
            //继续组装查询对象
            nativeSearchQueryBuilder.withHighlightFields(field);
        }
        //交给es查询
        SearchHits<ProdEs> searchHits = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), ProdEs.class);
        //手动封装结果集
        ArrayList<ProdEs> prodEs = new ArrayList<>();
        searchHits.forEach(searchHit->{
            ProdEs prodEs1 = searchHit.getContent();
            //高亮处理
            if (StringUtils.hasText(keywords)){
                String prodName = searchHit.getHighlightField("prodName").get(0);
                prodEs1.setProdName(prodName);
            }
            prodEs.add(prodEs1);
        });
        prodEsPage.setTotal(searchHits.getTotalHits());
        prodEsPage.setRecords(prodEs);
        return prodEsPage;
    }

    /**
     * 排序的处理
     * @param sort
     * @return
     */
    private SortBuilder mySort(Integer sort) {
        if (sort == null){
            return SortBuilders.fieldSort("positiveRating").order(SortOrder.DESC);
        }
        switch (sort){
            case 0:
                //综合排序  好评率
                return SortBuilders.fieldSort("positiveRating").order(SortOrder.DESC);
            case 1:
                //销量
                return SortBuilders.fieldSort("soldNum").order(SortOrder.DESC);
            case 2:
                //价格
                return SortBuilders.fieldSort("price").order(SortOrder.ASC);
            default:
                return null;
        }
    }
}
